package com.sgy.spring_ioc_xml_anno.factory;

import com.sgy.spring_ioc_xml_anno.utils.TransactionManager;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.cglib.proxy.Enhancer;
import org.springframework.cglib.proxy.MethodInterceptor;
import org.springframework.cglib.proxy.MethodProxy;
import org.springframework.stereotype.Component;

import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;

/**
 * 代理对象工厂：生成代理对象
 */
@Component("proxyFactory")
public class ProxyFactory {

    @Autowired
    @Qualifier("transactionManager")
    private TransactionManager transactionManager;

    public void setTransactionManager(TransactionManager transactionManager) {
        this.transactionManager = transactionManager;
    }

    /**
     * jdk动态代理
     * @param object 被代理对象
     * @return
     */
    public Object getJdkProxy(Object object) {
        return Proxy.newProxyInstance(object.getClass().getClassLoader(), object.getClass().getInterfaces(), new InvocationHandler() {
            @Override
            public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
                Object result = null;
                try {
                    // 开启事务
                    transactionManager.beginTransaction();
                    result = method.invoke(object, args);
                    // 提交事务
                    transactionManager.commitTransaction();
                } catch (Exception e) {
                    // 回滚事务
                    transactionManager.rollbackTransaction();
                    throw e;
                }
                return result;
            }
        });
    }

    /**
     * cglib动态代理
     * @param object 被代理对象
     * @return
     */
    public Object getCglibProxy(Object object) {
        return Enhancer.create(object.getClass(), new MethodInterceptor() {
            @Override
            public Object intercept(Object obj, Method method, Object[] args, MethodProxy proxy) throws Throwable {
                Object result = null;
                try {
                    // 开启事务
                    transactionManager.beginTransaction();
                    result = method.invoke(object, args);
                    // 提交事务
                    transactionManager.commitTransaction();
                } catch (Exception e) {
                    // 回滚事务
                    transactionManager.rollbackTransaction();
                    throw e;
                }
                return result;
            }
        });
    }
}
